package com.levi.controller;

import com.alibaba.fastjson.JSON;
import com.levi.controller.order.OrderControllerApi;
import com.levi.controller.product.ProductControllerApi;
import com.levi.pojo.Orders;
import com.levi.producer.OrderProducer;
import com.levi.service.OrderService;
import com.levi.vo.OrderDto;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController implements OrderControllerApi {

    @Autowired
    private OrderService orderService;

    @Resource
    private ProductControllerApi productControllerApi;

    @Autowired
    private OrderProducer producer;

    @Override
    @GlobalTransactional
    public Boolean create(Integer id, Integer count) {
       // TODO 创建订单过程中可能会出现异常
        Orders orders = new Orders();
        orders.setId(10);
        orders.setProductCount(count);
        orders.setProductId(id);
        orderService.save(orders);
        System.out.println("订单创建成功！！");
        String result = productControllerApi.decutProduct(id, count);
        return "success".equals(result);
    }

    @Override
    public String gateway() {
        return "gateway sucess!!";
    }

    @Override
    public String index() {
        return "index!!!";
    }

    @Override
    public String createOrder(OrderDto orderDto) {
        Orders order = new Orders();
        BeanUtils.copyProperties(orderDto,order);
        order.setId(901);
        String topic = "order";
        try {
            producer.send(JSON.toJSONString(order), topic);
        } catch (MQClientException e) {
            e.printStackTrace();
            return "fail";
        }
        return "success";
    }


}
